part of _;

extension on ProductDetailPage {
  void controller_initData() {
    void initVideo() {
      videoController = VideoPlayerController.network(model!.items_assets.first.video);
      chewieController = ChewieController(
        videoPlayerController: videoController!,
        autoInitialize: true,
        autoPlay: true,
        looping: false,
        //showControls: !(yIsWeb && defaultTargetPlatform == TargetPlatform.android),
        errorBuilder: (context, errorMessage) => Center(child: Icon(Icons.error_outline, color: Colors.white, size: 50)),
      );
      videoController!.setVolume(0);
      VoidCallback? listener;
      listener = () {
        if (!isPlaying && chewieController!.isPlaying) {
          yRun(() {
            videoController!.removeListener(listener!);
            if (!mounted || !yIsAlive) return;
            setState(() => isPlaying = true);
          }, delay: 2000);
        }
      };
      videoController!.addListener(listener);
    }

    yPost<ProductDetailModel>(IFinal.Jkids.getProductDetail, {
      "id": spuId,
    }, (isSuccess, results, code, message) {
      if (isSuccess) {
        model = results!.first;
        if (model!.items_assets.first.video.isNotEmpty) initVideo();
        setState(() {});
      } else
        yShowBuilder("数据加载失败，是否重试？\n$message", () => controller_initData(), () => yFinish(), false);
    }, onModel: (map) => ProductDetailModel.fromJson(map), showProgress: false, cacheEnable: true);
  }

  void controller_showMore() {
    SharesdkPlugin.showMenu(
      null,
      [ShareSDKPlatforms.qq, ShareSDKPlatforms.qqSeries, ShareSDKPlatforms.qZone, ShareSDKPlatforms.wechatSession, ShareSDKPlatforms.wechatSeries, ShareSDKPlatforms.wechatTimeline, ShareSDKPlatforms.weChatFavorites],
      SSDKMap()
        ..setGeneral(
          //标题
          YConfig.appName,
          //文本
          model!.title,
          //图片数组iOS使用
          model!.items_assets.map((e) => e.img).toList(),
          //url图片地址
          model!.items_assets.first.img,
          //本地图片路径
          "",
          //url地址
          "",
          //标题url地址
          "",
          //音乐url地址
          "http://i.y.qq.com/v8/playsong.html?hostuin=0&songid=&songmid=002x5Jje3eUkXT&_wv=1&source=qq&appshare=iphone&media_mid=002x5Jje3eUkXT",
          //视频url地址
          model!.items_assets.first.video,
          //文件地址
          "",
          //分享类型
          SSDKContentTypes.webpage,
        ),
      (state, platform, userData, contentEntity, error) {
        if (state != SSDKResponseState.Success) {
          if (error.rawData != null) yToast("三方分享失败：${error.rawData}");
          return;
        }
        yToast("三方分享成功");
      },
    );
  }

  void controller_showSelectSku() {
    final gridImage_space = 10.0;
    final gridImage_column = 3;
    final gridImage_size = (yScreenSize().width - gridImage_space * 2 - gridImage_space * (gridImage_column - 1)) / gridImage_column;
    var count_cart = 1;
    MyNumPickerController? myNumPickerController;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return StatefulBuilder(
          builder: (_, setDialogState) {
            return Container(
              height: yScreenSize().height / 4 * 3,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topRight: Radius.circular(15), topLeft: Radius.circular(15))),
              child: SafeArea(
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        YImageCorner(70, 70, controller_getSelectType().img, 5, fit: BoxFit.cover),
                        YSpacer(width: 10),
                        Expanded(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(controller_getSelectType().title, style: TextStyle(fontSize: 16)),
                                    YSpacer(height: 15),
                                    Row(
                                      children: [
                                        Text("￥", style: TextStyle(color: YConfig.themeColor, fontSize: 14)),
                                        Text(controller_getSelectType().money, style: TextStyle(color: YConfig.themeColor, fontSize: 20, fontWeight: FontWeight.bold)),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              YButton(
                                isInk: true,
                                padding: EdgeInsets.all(10),
                                child: Container(
                                  decoration: BoxDecoration(border: Border.all(color: Colors.grey, width: 2), borderRadius: BorderRadius.circular(99)),
                                  child: Icon(Icons.close, color: Colors.grey, size: 15),
                                ),
                                onTap: () => Navigator.pop(context),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    YSpacer(height: 15),
                    Divider(height: 1),
                    Expanded(
                      child: MyScrollView(
                        physics: BouncingScrollPhysics(),
                        children: [
                          YSpacer(height: 10),
                          Row(
                            children: [
                              Expanded(child: Text("商品规格(${model!.items_sku.length})")),
                              YButton(
                                isInk: true,
                                child: Row(
                                  children: [
                                    Icon(isTypeShowGrid ? Icons.format_list_bulleted : Icons.grid_view, size: 20),
                                    YSpacer(width: 2),
                                    Text(isTypeShowGrid ? "列表" : "大图"),
                                  ],
                                ),
                                onTap: () => setDialogState(() => isTypeShowGrid = !isTypeShowGrid),
                              ),
                            ],
                          ),
                          YSpacer(height: 10),
                          YAnimatedSwitcher(
                            duration: 100,
                            child: isTypeShowGrid
                                ? GridView.builder(
                                    primary: false,
                                    shrinkWrap: true,
                                    padding: EdgeInsets.zero,
                                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: gridImage_column, mainAxisSpacing: gridImage_space, crossAxisSpacing: gridImage_space, childAspectRatio: 0.7),
                                    itemCount: model!.items_sku.length,
                                    itemBuilder: (context, index) {
                                      final item_type = model!.items_sku[index];
                                      return Stack(
                                        fit: StackFit.expand,
                                        children: [
                                          ClipRRect(
                                            borderRadius: BorderRadius.circular(5),
                                            child: Container(
                                              color: Colors.grey.shade200,
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  YImage(gridImage_size, gridImage_size, item_type.img, fit: BoxFit.cover),
                                                  Expanded(
                                                    child: Container(
                                                      padding: EdgeInsets.all(5),
                                                      child: Column(
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          Expanded(
                                                            child: Text(
                                                              "${item_type.title} (销量:${item_type.count_sales})".fixAutoLines(),
                                                              maxLines: 1,
                                                              overflow: TextOverflow.ellipsis,
                                                              style: TextStyle(fontSize: 13, color: item_type.isSelect ? YConfig.themeColor : (item_type.count_left > 0 ? Colors.black : Colors.grey)),
                                                            ),
                                                          ),
                                                          Text("￥${item_type.money}", style: TextStyle(fontSize: 12, color: item_type.isSelect ? YConfig.themeColor : Colors.grey)),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          YButton(
                                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: item_type.isSelect ? YConfig.themeColor : Colors.transparent)),
                                            child: YEmpty(),
                                            enable: item_type.count_left > 0,
                                            onTap: () {
                                              myNumPickerController?.setValue(1);
                                              model!.items_sku.forEach((element) => element.isSelect = false);
                                              item_type.isSelect = true;
                                              setDialogState(() {});
                                            },
                                          ),
                                          Positioned(
                                            right: 0,
                                            child: YButton(
                                              color: Colors.black.withAlpha(20),
                                              isInk: true,
                                              padding: EdgeInsets.all(5),
                                              child: Icon(Icons.fullscreen_rounded, color: Colors.white),
                                              onTap: () => yIntent(ShowPicturePage(pictures: model!.items_sku.map((e) => e.img).toList(), index: index)),
                                            ),
                                          ),
                                        ],
                                      );
                                    },
                                  )
                                : ListView.builder(
                                    primary: false,
                                    shrinkWrap: true,
                                    padding: EdgeInsets.zero,
                                    itemCount: model!.items_sku.length,
                                    itemBuilder: (context, index) {
                                      final item_type = model!.items_sku[index];
                                      return YButton(
                                        height: 40,
                                        decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: item_type.isSelect ? YConfig.themeColor : Colors.transparent)),
                                        margin: EdgeInsets.only(bottom: gridImage_space),
                                        padding: EdgeInsets.all(5),
                                        enable: item_type.count_left > 0,
                                        child: Row(
                                          children: [
                                            YImageCorner(30, 30, item_type.img, 5, fit: BoxFit.cover),
                                            YSpacer(width: 5),
                                            Expanded(
                                              child: Text(
                                                "${item_type.title} (销量:${item_type.count_sales})".fixAutoLines(),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(fontSize: 13, color: item_type.isSelect ? YConfig.themeColor : (item_type.count_left > 0 ? Colors.black : Colors.grey)),
                                              ),
                                            ),
                                            YSpacer(width: 5),
                                            Text("￥${item_type.money}", style: TextStyle(color: Colors.grey)),
                                          ],
                                        ),
                                        onTap: () {
                                          myNumPickerController?.setValue(1);
                                          model!.items_sku.forEach((element) => element.isSelect = false);
                                          item_type.isSelect = true;
                                          setDialogState(() {});
                                        },
                                      );
                                    },
                                  ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      children: [
                        Text("数量："),
                        YExpanded(),
                        MyNumPicker(
                          value: count_cart,
                          max: model!.items_sku.firstWhere((element) => element.isSelect).count_left,
                          onChange: (value) => count_cart = value,
                          onCreate: (controller) => myNumPickerController = controller,
                        ),
                      ],
                    ),
                    YSpacer(height: 20),
                    Container(
                      padding: EdgeInsets.only(top: gridImage_space),
                      child: Row(
                        children: [
                          Expanded(
                            child: YButton(
                              height: 40,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  begin: Alignment.centerLeft,
                                  end: Alignment.centerRight,
                                  colors: [Color.fromARGB(255, 242, 202, 70), Color.fromARGB(255, 239, 151, 56)],
                                ),
                              ),
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(20), bottomLeft: Radius.circular(20)),
                              padding: EdgeInsets.only(left: 5),
                              child: Text("加入购物车", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                              onTap: () {
                                yPost<ProductDetailModel>(IFinal.Jkids.addCart, {
                                  "spu": spuId,
                                  "sku": controller_getSelectType().id,
                                  "count": count_cart,
                                }, (isSuccess, results, code, message) {
                                  if (isSuccess) {
                                    Navigator.pop(context);
                                    yToast("加入购物车成功");
                                    setState(() => model!.count_carts = results!.first.count_carts);
                                    yBroadcast_send(IFinal.Broadcasts.refreshCart);
                                  }
                                }, onModel: (map) => ProductDetailModel.fromJson(map));
                              },
                            ),
                          ),
                          Expanded(
                            child: YButton(
                              height: 40,
                              decoration: BoxDecoration(gradient: IFinal.Colors.btnThemeGradient),
                              borderRadius: BorderRadius.only(topRight: Radius.circular(20), bottomRight: Radius.circular(20)),
                              padding: EdgeInsets.only(right: 5),
                              child: Text("立即购买", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                              onTap: () {
                                yPost<CartMainModel>(IFinal.Jkids.addBuy, {
                                  "spu": spuId,
                                  "sku": controller_getSelectType().id,
                                  "count": count_cart,
                                }, (isSuccess, results, code, message) {
                                  if (isSuccess) {
                                    Navigator.pop(context);
                                    yIntent(OrderConfirmPage(results!));
                                  }
                                }, onModel: (map) => CartMainModel.fromJson(map));
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  ProductDetailModel_Sku controller_getSelectType() {
    var result = model!.items_sku.first;
    model!.items_sku.forEach((item_type) {
      if (item_type.isSelect) result = item_type;
    });
    return result;
  }

  void controller_save() {
    setState(() => isSaveLoading = true);
    yPost<ProductDetailModel>(IFinal.Jkids.toggleSaveProduct, {
      "id": spuId,
    }, (isSuccess, results, code, message) {
      setState(() => isSaveLoading = false);
      if (isSuccess) setState(() => model!.isSave = results!.first.isSave);
    }, onModel: (map) => ProductDetailModel.fromJson(map), showProgress: false);
  }

  void controller_showParam() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Container(
          height: yScreenSize().height / 4 * 3,
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topRight: Radius.circular(15), topLeft: Radius.circular(15))),
          child: SafeArea(
            child: Column(
              children: [
                YSpacer(height: 15),
                Text("商品参数", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                YSpacer(height: 15),
                Expanded(
                  child: ListView.builder(
                    physics: BouncingScrollPhysics(),
                    padding: EdgeInsets.only(left: 15, right: 15),
                    itemCount: model!.items_param.length,
                    itemBuilder: (context, index) {
                      final item_param = model!.items_param[index];
                      return Column(
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: 10, bottom: 10),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Container(
                                  width: 70,
                                  child: Text(item_param.title.fixAutoLines()),
                                ),
                                YSpacer(width: 10),
                                Expanded(
                                  child: Text(item_param.content.fixAutoLines()),
                                ),
                              ],
                            ),
                          ),
                          Divider(height: 1),
                        ],
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
